package adventure.commands.admin;

import adventure.*;
import adventure.commands.*;
import colour.ColourUtil;
import player.*;

/**
 *
 * @author Michael Hanns
 *
 */
public class MovePlayer extends AbstractCommand {

    public MovePlayer(Adventure a) {
        super(a, new String[]{"MOVEPLAYER"});
    }

    @Override
    public String validateAndExecute(Player p, String[] args) {
        if (p.isAdmin()) {
            if (args.length == 5) {
                return changeName(p, args[1], args[2], args[3], args[4]);
            } else {
                return "Move who to where?\nSyntax: moveplayer <target player> <x> <y> <z>";
            }
        } else {
            return "Command not recognised.";
        }
    }

    private String changeName(Player admin, String target, String x, String y, String z) {
        Player targetPlayer = players.getOnlinePlayer(target);

        if (targetPlayer.getID() > 0) {
            int xCoord = parseCoordinate(x);
            int yCoord = parseCoordinate(y);
            int zCoord = parseCoordinate(z);

            if (xCoord == -1 || yCoord == -1 || zCoord == -1) {
                return "Invalid coordinates!\nSyntax: moveplayer <target player> <x> <y> <z>";
            }

            if (rooms.roomExists(xCoord, yCoord, zCoord)) {
                rooms.leaveRoom(targetPlayer);
                ((PlayerEdit) targetPlayer).setX(xCoord);
                ((PlayerEdit) targetPlayer).setY(yCoord);
                ((PlayerEdit) targetPlayer).setZ(zCoord);
                rooms.enterRoom(targetPlayer);
                out.broadcastToPlayer(targetPlayer, adv.printRoom(targetPlayer) + "\n");
                out.broadcastToPlayer(targetPlayer,
                        ColourUtil.colourise(admin.getAliveName(), ColourUtil.player)
                        + " has moved you.");

                return "You have moved "
                        + ColourUtil.colourise(targetPlayer.getAliveName(), ColourUtil.player)
                        + " to (" + xCoord + ", " + yCoord + ", " + zCoord + ").";
            } else {
                return "Player destination does not exist!";
            }
        } else {
            targetPlayer = players.getOfflinePlayer(target);

            if (targetPlayer.getID() > 0) {
                return "Player "
                        + ColourUtil.colourise(targetPlayer.getAliveName(), ColourUtil.player)
                        + " must be online to move their location.";
            }
        }
        return "Player " + target + " does not exist!";
    }

    private int parseCoordinate(String x) {
        try {
            int xCoord = Integer.parseInt(x);

            return xCoord;
        } catch (NumberFormatException e) {
            return -1;
        }
    }
}
